﻿namespace Vboot.App.My;

/// <summary>
/// DEMO分类管理
/// </summary>
public class MyDemoCateApi : IDynamicApiController
{
    private readonly MyDemoCateService _service;

    public MyDemoCateApi(MyDemoCateService service)
    {
        _service = service;
    }

    /// <summary>
    /// 获取所有分类-用于分类选择下拉框
    /// </summary>
    [QueryParameters]
    public async Task<dynamic> GetTreea()
    {
        var treeList = await _service.repo.Context
            .Queryable<MyDemoCate>().OrderBy(it => it.ornum)
            .ToTreeAsync(it => it.children, it => it.pid, null);
        return treeList;
    }

    /// <summary>
    /// 获取除自身及子节点外的分类
    /// </summary>
    [QueryParameters]
    public async Task<dynamic> GetTreez(string id)
    {
        var treeList = await _service.repo.Context
            .Queryable<MyDemoCate>()
            .WhereIF(!string.IsNullOrWhiteSpace(id), t => t.id != id)
            .OrderBy(it => it.ornum)
            .ToTreeAsync(it => it.children, it => it.pid, null);
        return treeList;
    }

    /// <summary>
    /// 获取分类treeTable数据
    /// </summary>
    [QueryParameters]
    public async Task<dynamic> GetTree(string name)
    {
        var treeList = await _service.repo.Context
            .Queryable<MyDemoCate>()
            .WhereIF(!string.IsNullOrWhiteSpace(name), t => t.name.Contains(name.Trim()))
            .OrderBy(it => it.ornum)
            .ToTreeAsync(it => it.children, it => it.pid, null);
        return treeList;
    }

    /// <summary>
    /// 获取单个分类详细信息
    /// </summary>
    public async Task<MyDemoCate> GetOne(string id)
    {
        var menu = await _service.SingleAsync(id);
        if (menu.pid != null)
        {
            menu.pname = await _service.repo.Context.Queryable<MyDemoCate>()
                .Where(it => it.id == menu.pid).Select(it => it.name).SingleAsync();
        }

        return menu;
    }

    /// <summary>
    /// 新增DEMO分类
    /// </summary>
    public async Task Post(MyDemoCate menu)
    {
        await _service.InsertAsync(menu);
    }

    /// <summary>
    /// 更新DEMO分类
    /// </summary>
    public async Task Put(MyDemoCate menu)
    {
        await _service.UpdateAsync(menu);
    }

    /// <summary>
    /// 删除DEMO分类
    /// </summary>
    public async Task Delete(string ids)
    {
        var idArr = ids.Split(",");
        foreach (var id in idArr)
        {
            var count = await
                _service.repo.Context.Queryable<MyDemoCate>().Where(it => it.pid == id).CountAsync();
            if (count > 0)
            {
                throw new Exception("有子分类无法删除");
            }
        }

        await _service.DeleteAsync(ids);
    }
}